package com.traveling.hztraveling.interceptor;

import com.traveling.hztraveling.context.BaseContext;
import com.traveling.hztraveling.entity.po.HzUser;
import com.traveling.hztraveling.mapper.HzUserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,Long> redisTemplate;

    @Autowired
    private HzUserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getHeader("userId") != null){
            BaseContext.setCurrentId(Long.valueOf(request.getHeader("userId")));
            System.out.println("拦截器拦截,userId为"+BaseContext.getCurrentId());
            HzUser user = userMapper.selectById(BaseContext.getCurrentId().intValue());
            user.setPassword(null);
            redisTemplate.opsForHash().put("userId",BaseContext.getCurrentId(),user);
            return true;
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
